<?php

namespace App\Supports\Payment\Methods\Balance;

use App\Models\BlindBoxOrder;
use App\Models\UserCoupon;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Events\OrderPaidEvent;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;
use Brick\Math\RoundingMode;
use App\Events\BoxOrderPaidEvent;
use Illuminate\Support\Facades\Log;

class PayBoxOrder extends Method implements MethodPay
{
	protected function isBalanceEnough($order)
	{
		return big_decimal($order->user->balance)
			->isGreaterThanOrEqualTo($order->price_lowest);
	}
	
	public function validate($order = null)
	{

		/*if ($order->isPaid()) {
			fail('目标订单已支付');
		}*/
		if ($order->is_taken) {
			fail('目标订单已被领取');
		}

		if (!$this->isBalanceEnough($order)) {
			fail('可用账户余额不足');
		}
	
		
	}
	
	public function info($order = null) {}
	
	public function pay($order = null)
	{

		$this->validate($order);
		return DB::transaction(function () use ($order) {
			$order = BlindBoxOrder::find($order->id);

			$balances = $order->box_price;
			
			if($order->user_coupon_id){
				$coupon = UserCoupon::find($order->user_coupon_id)->coupon()->first();
				if($coupon->coupon_category == 'box'){
					$balances = (string)big_decimal($order->box_price)->minus($coupon->decrement_price)->toScale(2, RoundingMode::HALF_UP);
				}
				UserCoupon::find($order->user_coupon_id)->update(['is_used'=>1]);
				//dd($coupon->update(['is_used'=>true]););
			}
			$order->update(['paid_at' => Carbon::now(), 'paid_method' => 'balance' ,'price_lowest' => $balances]);
			
            $data = ['blind_box_order_id' => $order->id];
            account_balances($order->user)->minusBoxOrderPaid($balances, $data);

            event(new BoxOrderPaidEvent($order));
			
			//$order->unsetRelations();
			return $order;
		
		});
	}
}
